#!/usr/bin/env bash

###
#
#  bin: /opt/bin/flanneld
#
###

# source ./02.k8s_variable.sh


cp ./flannel/mk-docker-opts.sh /usr/bin/mk-docker-opts.sh
chmod a+x /usr/bin/mk-docker-opts.sh

cp -r ./flannel/sysconfig/  /etc/

cat > /lib/systemd/system/flanneld.service <<EOF
[Unit]
Description=Flanneld overlay address etcd agent
Documentation=https://github.com/coreos/flannel
After=network.target
After=network-online.target
Wants=network-online.target
After=etcd.service
Before=docker.service

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/flanneld
EnvironmentFile=-/etc/sysconfig/docker-network
ExecStart=/bin/bash -c "/opt/bin/flanneld --etcd-endpoints=\$FLANNEL_ETCD_ENDPOINTS --etcd-prefix=\$FLANNEL_ETCD_PREFIX \$FLANNEL_OPTIONS"


ExecStartPost=/usr/bin/mk-docker-opts.sh -k DOCKER_NETWORK_OPTIONS -d /run/flannel/docker

Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
#RequiredBy=docker.service
EOF

systemctl daemon-reload

# 启动 flanneld
systemctl start flanneld.service
systemctl enable flanneld.service

# check
cat /run/docker_opts.env
cat /run/flannel/subnet.env




# 将环境变量，添加docker启动参数中
# vim /lib/systemd/system/docker.service
# EnvironmentFile=/run/flannel/docker
# ExecStart=/usr/bin/dockerd ${DOCKER_OPT_BIP} ${DOCKER_OPT_IPMASQ} ${DOCKER_OPT_MTU}


systemctl daemon-reload
# 启动
systemctl stop docker
systemctl restart flanneld
# 开机自启
systemctl enable flanneld.service
systemctl start docker
# 检查
ip a  | grep flannel
ip a  | grep docker

echo "docker, flannel =====> successfully"
